package com.yanqu.road.server.gameplayer.module.activity.unionwar;

import com.yanqu.road.entity.activity.ActivityConditionInfo;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.ActivityRewardResult;
import com.yanqu.road.entity.activity.UserActivityConditionData;
import com.yanqu.road.entity.activity.unionwar.*;
import com.yanqu.road.entity.activity.unionwar.enums.eTimeInfoPeriodType;
import com.yanqu.road.entity.activity.unionwar.result.CurrentTimeInfo;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.log.LogUnionWarActivityGuess;
import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.entity.union.UnionBaseInfo;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroupUnion;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroupUser;
import com.yanqu.road.entity.unionwar.GuessUnionInfo;
import com.yanqu.road.entity.unionwar.UserUnionWarGuessData;
import com.yanqu.road.logic.bussiness.activity.UnionWarActivityBusiness;
import com.yanqu.road.pb.activity.ActivityProto;
import com.yanqu.road.pb.activity.unionwar.UnionWarActivityServerProto;
import com.yanqu.road.pb.cross.activity.CrossActivityProto;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.banquet.BanquetModule;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.player.DecorationModule;
import com.yanqu.road.server.logic.unionwar.UnionWarActivityData;
import com.yanqu.road.server.logic.unionwar.condition.BaseUnionWarActivityCondition;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.unionwar.UnionPhaseWarMgr;
import com.yanqu.road.server.manger.activity.unionwar.UnionWar;
import com.yanqu.road.server.manger.activity.unionwar.UnionWarActivityMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.manger.union.GameUnionActivityGroupMgr;
import com.yanqu.road.server.pb.UnionWarActivityPb;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class UnionWarActivityModule extends GeneralModule {
    private Map<Integer, Map<Integer, UserUnionWarGuess>> unionWarGuessMap;
    private Map<Integer, Map<Integer, UnionWarActivityData>> activityDataMap;

    //activityId
    private Map<Integer, List<UnionWarSessionReward>> battleRewardMap;

    public UnionWarActivityModule(GamePlayer player) {
        super(player);
    }

    public Map<Integer, Map<Integer, UnionWarActivityData>> getActivityDataMap() {
        return activityDataMap;
    }

    public Map<Integer, List<UnionWarSessionReward>> getBattleRewardMap() {
        return battleRewardMap;
    }

    @Override
    public boolean loadData() {
        List<Integer> activityIdList = new ArrayList<>();
        activityDataMap = new ConcurrentHashMap<>();
        unionWarGuessMap = new ConcurrentHashMap<>();
        Map<Integer, Map<Integer, UserUnionWarGuessData>> unionWarGuessDataMap = UnionWarActivityBusiness.getUserUnionWarGuessDataMap(player.getUserId());
        Map<Integer, ActivityInfo> activityInfoMap = UnionWarActivityMgr.getOpenActivityInfoMap();
        for (ActivityInfo activityInfo : activityInfoMap.values()) {
            if (activityInfo != null) {
                int activityId = activityInfo.getActivityId();
                activityIdList.add(activityInfo.getActivityId());
                Map<Integer, UserUnionWarGuessData> dataMap = unionWarGuessDataMap.get(activityId);
                if (dataMap != null) {
                    for (UserUnionWarGuessData guessData : dataMap.values()) {
                        if(!unionWarGuessMap.containsKey(guessData.getActivityId())){
                            unionWarGuessMap.put(guessData.getActivityId(), new ConcurrentHashMap<>());
                        }
                        unionWarGuessMap.get(activityId).put(guessData.getStage(), new UserUnionWarGuess(player, activityId, guessData.getStage(), guessData));
                    }
                }

                Map<Integer, List<UserActivityConditionData>> userActivityConditionDataMap = UnionWarActivityBusiness.getUserActivityConditionDataMap(player.getUserId(), activityId);
                if (userActivityConditionDataMap != null) {
                    for (Map.Entry<Integer, List<UserActivityConditionData>> dataEntry : userActivityConditionDataMap.entrySet()) {
                        addActivity(activityInfo, dataEntry.getValue(), dataEntry.getKey(), false);
                    }
                }
                addNewActivity(activityInfo);
            }
        }
        if(activityIdList.size() > 0) {
            battleRewardMap = UnionWarActivityBusiness.getUserBattleRewardMap(player.getUserId(), activityIdList);
        }else {
            battleRewardMap = new ConcurrentHashMap<>();
        }
        return true;
    }

    public void addNewActivity(ActivityInfo activityInfo) {
        synchronized (this) {
            if (null != activityInfo) {
                Map<Integer, List<ActivityConditionInfo>> dataMap = UnionPhaseWarMgr.getActivityConditionInfoMap(activityInfo.getActivityId());
                if (dataMap != null) {
                    for (int type : dataMap.keySet()) {
                        addActivity(activityInfo, new ArrayList<>(), type, true);
                    }
                }
                Map<Integer, UnionWarActivityData> tempActivityDataMap = getActivityDataMap(activityInfo.getActivityId());
                if (tempActivityDataMap != null) {
                    for (UnionWarActivityData activityData : tempActivityDataMap.values()) {
                        for (BaseUnionWarActivityCondition baseActivityCondition : activityData.getBaseActivityConditionList()) {
                            if (null != baseActivityCondition) {
                                baseActivityCondition.initValue();
                            }
                        }
                    }
                }
            }
        }
    }

    private Map<Integer, UnionWarActivityData> getActivityDataMap(int activityId) {
        return activityDataMap.get(activityId);
    }

    private void addActivity(ActivityInfo activityInfo, List<UserActivityConditionData> conditionDataList, int type, boolean isNew) {
        synchronized (this) {
            if (null != activityInfo) {
                if (!activityDataMap.containsKey(activityInfo.getActivityId())) {
                    activityDataMap.put(activityInfo.getActivityId(), new ConcurrentHashMap<>());
                }
                Map<Integer, UnionWarActivityData> dataMap = activityDataMap.get(activityInfo.getActivityId());
                if (dataMap.containsKey(type)) {
                    return;
                }
                List<ActivityConditionInfo> conditionInfoList = UnionPhaseWarMgr.getActivityConditionInfoList(activityInfo.getActivityId(), type);
                if (null == conditionInfoList) {
                    return;
                }

                UnionWarActivityData activityData = new UnionWarActivityData(player, activityInfo, conditionDataList);
                for (ActivityConditionInfo conditionInfo : conditionInfoList) {
                    if (activityData.continueAdd(conditionInfo.getType())) {
                        BaseUnionWarActivityCondition baseActivityCondition = BaseUnionWarActivityCondition.createActivityCondition(player, activityData, conditionInfo);
                        if (null != baseActivityCondition) {
                            activityData.addCondition(baseActivityCondition);
                            if (isNew) {
                                UserActivityConditionData userConditionData = ActivityMgr.initUserActivityConditionData(player, conditionInfo);
                                activityData.addUserActivityConditionData(userConditionData);
                            }
                        }
                    }
                }
                dataMap.put(type, activityData);
                activityData.addToPlayer();
            }
        }
    }

    public void onActivityDataChange(UnionWarActivityData activityData) {
        ActivityProto.ActivityDataMsg.Builder dataMsg = UnionWarActivityPb.parseActivityDataMsg(activityData);
        if (null != dataMsg) {
            player.sendPacket(Protocol.U_UNION_WAR_ACTIVITY_CONDITION_DATA_SYNC, dataMsg);
        }
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public boolean saveData() {
        if(battleRewardMap != null) {
            for (int activityId : battleRewardMap.keySet()) {
                List<UnionWarSessionReward> list = battleRewardMap.get(activityId);
                int size = list.size();
                for (int i = 0; i < size; i++) {
                    UnionWarSessionReward resultReward = list.get(i);
                    if (resultReward.isInsertOption()) {
                        UnionWarActivityBusiness.addUnionWarBattleResultReward(resultReward);
                    } else if (resultReward.isUpdateOption()) {
                        UnionWarActivityBusiness.updateUnionWarBattleResultReward(resultReward);
                    }
                }
            }
        }

        for (Map<Integer, UserUnionWarGuess> guessMap : unionWarGuessMap.values()) {
            for (UserUnionWarGuess unionWarGuess : guessMap.values()) {
                unionWarGuess.save();
            }
        }
        for (Map<Integer, UnionWarActivityData> dataMap : activityDataMap.values()) {
            for (UnionWarActivityData activityData : dataMap.values()) {
                List<UserActivityConditionData> userActivityConditionDataList = new ArrayList<>(activityData.getUserActivityConditionDataList());
                for (UserActivityConditionData data : userActivityConditionDataList) {
                    if (data.isInsertOption()) {
                        UnionWarActivityBusiness.addUserActivityConditionData(data);
                    } else if (data.isUpdateOption()) {
                        UnionWarActivityBusiness.updateUserActivityConditionData(data);
                    }
                }
            }
        }
        return true;
    }

    @Override
    public void afterLogin() {
        if(!SystemOpenMgr.systemOpen(player, eSystemId.UnionWarActivity.getValue())){
            return;
        }
        for(ActivityInfo activityInfo : UnionWarActivityMgr.getOpenActivityInfo()){
            addNewActivity(activityInfo);
        }
        syncActivity();
        for(ActivityInfo activityInfo : UnionWarActivityMgr.getOpenActivityInfo()){
            syncActivityConfigData(activityInfo);
            syncUserActivityData(activityInfo);
        }
    }

    public void syncUserActivityData(ActivityInfo activityInfo){
        if(!SystemOpenMgr.systemOpen(player, eSystemId.UnionWarActivity.getValue())){
            return;
        }
        player.sendPacket(Protocol.U_UNION_WAR_USER_DATA_INFO_SYNC, buildUserDataInfoTempBuilder(activityInfo.getActivityId()));
    }

    public void syncActivityConfigData(ActivityInfo activityInfo){
        UnionWar unionWar = UnionPhaseWarMgr.getUnionWarMap().get(activityInfo.getActivityId());
        if(unionWar != null) {
            player.sendPacket(Protocol.U_UNION_WAR_ACTIVITY_CONFIG_SYNC,  UnionWarActivityPb.parseActivityConfigData(activityInfo, unionWar.getTimeInfoList()));
        }
    }

    public void syncActivity(){
        if(!SystemOpenMgr.systemOpen(player, eSystemId.UnionWarActivity.getValue())){
            return;
        }
        if(null != activityDataMap) {
            String language = player.getLanguage();
            List<UnionWarActivityData> list = new ArrayList<>();
            for(Map.Entry<Integer, Map<Integer, UnionWarActivityData>> entry : activityDataMap.entrySet()){
                for(Map.Entry<Integer, UnionWarActivityData> innerEntry : entry.getValue().entrySet()){
                        list.add(innerEntry.getValue());
                }
            }
            player.sendPacket(Protocol.U_UNION_WAR_ACTIVITY_DATA_SYNC, UnionWarActivityPb.parseActivityDataListMsg(list,
                    UnionWarActivityMgr.getOpenActivityInfo(), UnionWarActivityMgr.getActivityConditionInfoMap(),
                    UnionWarActivityMgr.getActivityMallInfoMap(), UnionWarActivityMgr.getActivityConfigMap(), language));
        }
    }


    /**
     * 获取玩家参赛的相关信息
     * @param activityId
     * @return
     */
    public UnionWarActivityServerProto.ActivityUserDataInfoRespMsg.Builder buildUserDataInfoTempBuilder(int activityId) {
        UnionWarActivityServerProto.ActivityUserDataInfoRespMsg.Builder respMsg = UnionWarActivityServerProto.ActivityUserDataInfoRespMsg.newBuilder();
        respMsg.setUnionPosition(4);
        UnionWarActivityServerProto.ActivityUserAdmissionTemp.Builder builder = UnionWarActivityServerProto.ActivityUserAdmissionTemp.newBuilder();
        UnionWar unionWar = UnionPhaseWarMgr.getUnionWarMap().get(activityId);
        if(unionWar != null){
            CurrentTimeInfo currentTimeInfo = unionWar.getCurrentTimeInfo();
            UnionQunyingTimeInfo timeInfo = currentTimeInfo.getTimeInfo();
            if(currentTimeInfo.getPeriodType() != null) {
                builder.setPeriodState(currentTimeInfo.getPeriodType().getIntValue());
            }
            builder.setActivityId(activityId);
            builder.setUnionJoin(false);
            builder.setHasAdmission(false);
            builder.setTimeId(0);
            if(timeInfo != null) {
                builder.setTimeId(timeInfo.getTimeId());
            }
            String unionUid = GameUnionActivityGroupMgr.getUnionUid(activityId, player.getUserId());
            if(!StringUtils.isNullOrEmpty(unionUid)){
                UnionActivityGroupUnion unionData = GameUnionActivityGroupMgr.getUnionData(activityId, player.getUserId());
                if(unionData != null && unionData.getUserMap().get(player.getUserId()) != null){
                    UnionActivityGroupUser groupUser = unionData.getUserMap().get(player.getUserId());
                    if(groupUser != null){
                        respMsg.setUnionPosition(groupUser.getPosition());
                    }
                }
                builder.setUnionJoin(unionWar.isJoin(unionUid));
                //是否进入决赛（取决赛第一轮）
                boolean joinFinals = unionWar.isJoinCurrentTimeInfo(unionUid, unionWar.getUnionQunyingTimeInfo(2, 1));
                builder.setJoinFinals(joinFinals);

                if(timeInfo != null){
                    builder.setTimeId(timeInfo.getTimeId());
                    if(unionWar.isJoinCurrentTimeInfo(unionUid, timeInfo)){
                        builder.setHasAdmission(true);
                        //是否有未派遣门客
                        respMsg.setRemainPatronsId(false);
                        List<UserPatrons> userPatronsList = player.getModule(PatronsModule.class).getUserPatronsList();
                        int allPatronsNum = userPatronsList.size();
                        if(unionWar.getUserPatronsSendMap().containsKey(player.getUserId())){
                            Map<Integer, UserPatronsSendTimes> userPatronsSendTimesMap = unionWar.getUserPatronsSendMap().get(player.getUserId());
                            for(UserPatronsSendTimes userPatronsSendTimes : userPatronsSendTimesMap.values()){
                                if(userPatronsSendTimes.getTimes() > 0) {
                                    allPatronsNum--;
                                }
                            }
                        }
                        if(allPatronsNum > 0){
                            respMsg.setRemainPatronsId(true);
                        }
                        //派遣情况
                        Map<Integer, UnionWarDispatchDetail> dispatchDetailMap = unionWar.getUnionWarDispatchDetailList(unionUid, timeInfo.getType());
                        if(dispatchDetailMap != null){
                            for(UnionWarDispatchDetail detail : dispatchDetailMap.values()){
                                if(detail.getPhase() >= timeInfo.getType() && detail.getPatronsMap().containsKey(player.getUserId())){
                                    builder.addJoinSession(detail.getSession());
                                }
                            }
                        }
                    }
                }
            }
            //排行榜红点
            String can = unionWar.isCanGetRewardMember(unionUid, 1, player.getUserId());
            if(!StringUtils.isNullOrEmpty(can)){
                respMsg.setCanGetRankReward1(true);
            }else {
                respMsg.setCanGetRankReward1(false);
            }
            can = unionWar.isCanGetRewardMember(unionUid, 2, player.getUserId());
            if(!StringUtils.isNullOrEmpty(can)){
                respMsg.setCanGetRankReward2(builder.getJoinFinals());
            }else {
                respMsg.setCanGetRankReward2(false);
            }

//            List<Long> canDispatchMemberList = unionWar.getCanDispatchMemberList(unionUid);
//            for (Long userId : canDispatchMemberList) {
//                CrossUnionMember unionMember = CrossUnionMgr.getUnionMember(unionUid, userId);
//                if (unionMember == null) {
//                    continue;
//                }
//                UnionWarActivityServerProto.UnionWarUnionMember.Builder member = UnionWarActivityServerProto.UnionWarUnionMember.newBuilder();
//                member.setUserId(userId);
//                member.setPlayerBaseData(PlayerBasePb.parsePlayerBaseTempMsg(unionMember.getUserBaseInfo()));
//                respMsg.addMember(member);
//            }
            respMsg.setRet(0);
        }else {
            respMsg.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            builder.setTimeId(0);
            builder.setActivityId(0);
            builder.setHasAdmission(false);
        }
        respMsg.setInfo(builder);
        return respMsg;
    }

    /**
     * 领取结果奖励
     * @param activityId
     * @param phase
     * @param session
     * @return
     */
    public ActivityRewardResult getBattleResultReward(int activityId, int phase, int session) {
        ActivityRewardResult result = new ActivityRewardResult();
        UnionWar unionWar = UnionPhaseWarMgr.getUnionWarMap().get(activityId);
        if(unionWar == null){
            result.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            return result;
        }
        CurrentTimeInfo currentTimeInfo = unionWar.getCurrentTimeInfo();
        //不在领奖期且没有周期
        if(currentTimeInfo.getTimeInfo() == null && currentTimeInfo.getPeriodType() != eTimeInfoPeriodType.ReceiveTime){
            result.setRet(GameErrorCode.E_UNION_WAR_ACTIVITY_OVER_RECEIVE_TIME);
            return result;
        }
        String unionUid = UnionWar.getUserUnionUid(activityId, player.getUserInfo());
        if(StringUtils.isNullOrEmpty(unionUid)){
            result.setRet(GameErrorCode.E_UNION_NO_JOIN_UNION);
            return result;
        }
        UnionWarUnionMember member = unionWar.getUnionWarUnionMember(unionUid, phase, session);
        if(member == null){
            //找分组
            int groupId = GameUnionActivityGroupMgr.getGroupId(activityId, player.getUserId());
            if(groupId == -1) {
                result.setRet(GameErrorCode.E_ACTIVITY_NO_JOIN);
                return result;
            }
        }else {
            if(!member.getUserIdList().contains(player.getUserId())){
                result.setRet(GameErrorCode.E_UNION_WAR_ACTIVITY_NO_GET_BATTLE_REWARD);
                return result;
            }
        }
        UnionWarDispatchDetail detail = unionWar.getUnionWarDispatchDetailList(unionUid, phase, session);
        if(detail == null || detail.getWinMark() == eUnionWarWinMark.Default.getValue()){
            result.setRet(GameErrorCode.E_UNION_WAR_ACTIVITY_NO_GET_BATTLE_REWARD);
            return result;
        }
        //未派遣,或者非轮空
        if(detail != null && detail.getWinMark() != eUnionWarWinMark.Bye.getValue()){
            if(!detail.getPatronsMap().containsKey(player.getUserId()) || detail.getPatronsMap().get(player.getUserId()).getPatrons().size() == 0){
                result.setRet(GameErrorCode.E_UNION_WAR_ACTIVITY_NO_GET_BATTLE_REWARD);
                return result;
            }
        }
        synchronized (battleRewardMap){
            UnionWarSessionReward resultReward = null;
            if(battleRewardMap.containsKey(activityId)){
                for(UnionWarSessionReward temp : battleRewardMap.get(activityId)){
                    if(temp.getPhase() == phase && temp.getSession() == session){
                        resultReward = temp;
                    }
                }
            }else{
                battleRewardMap.put(activityId, new ArrayList<>());
            }
            if(resultReward == null){
                resultReward = new UnionWarSessionReward();
                resultReward.setActivityId(activityId);
                resultReward.setPhase(phase);
                resultReward.setSession(session);
                resultReward.setUserId(player.getUserId());
                resultReward.setUnionUid(unionUid);
                resultReward.setInsertOption();
            }
            if(resultReward.isGetReward()) {
                result.setRet(GameErrorCode.E_UNION_WAR_ACTIVITY_HAD_GET_BATTLE_REWARD);
                return result;
            }
            long masterUserId = 0;
            UnionBaseInfo unionInfo = detail.getUnionInfo();
            if (unionInfo == null) {
                UnionBaseInfo unionBaseInfo = CrossUnionMgr.parseUnionBaseInfo(detail.getUnionUid());
                detail.setUnionInfo(unionBaseInfo);
            }
            unionInfo = detail.getUnionInfo();
            if (unionInfo != null) {
                masterUserId = unionInfo.getMasterUserId();
            }
            boolean isMaster = player.getUserId() == masterUserId;
            UnionQunyingTimeInfo timeInfo = unionWar.getUnionQunyingTimeInfo(phase, session);
            Property reward = unionWar.getBattleReward(timeInfo, detail.getWinMark() != eUnionWarWinMark.Lose.getValue(), isMaster);
            if(reward.isNothing()) {
                result.setRet(GameErrorCode.E_UNION_WAR_ACTIVITY_NO_GET_BATTLE_REWARD);
                return result;
            }
            player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.Activity, eLogMoneyType.UnionWarActivitySessionReward);
            resultReward.setGetReward(true);
            resultReward.setReward(PropertyHelper.parsePropertyToString(reward));
            if(resultReward.isInsertOption()) {
                battleRewardMap.get(activityId).add(resultReward);
            }
            result.setReward(resultReward.getReward());
        }
        return result;
    }

    private boolean checkInGuessTime(int stage, int activityId) {
        UnionWar unionWar = UnionPhaseWarMgr.getUnionWar(activityId);
        if (unionWar == null) {
            return false;
        }
        return unionWar.checkInGuessTime(stage);
    }


    private boolean checkInGuessRewardTime(int stage, int activityId) {
        UnionWar unionWar = UnionPhaseWarMgr.getUnionWar(activityId);
        if (unionWar == null) {
            return false;
        }
        return unionWar.checkInGetRewardTime(stage);
    }

    public UserUnionWarGuessData getGuessData(int activityId, int stage) {
        if (!unionWarGuessMap.containsKey(activityId)) {
            return null;
        }
        if (!unionWarGuessMap.get(activityId).containsKey(stage)) {
            return null;
        }
        return unionWarGuessMap.get(activityId).get(stage).getUserUnionWarGuessData();
    }

    /**
     * 竞猜
     * @param activityId 活动ID
     * @param guessUnionList 竞猜列表
     * @param stage 阶段
     */
    public int guess(int activityId, List<UnionWarActivityServerProto.UnionWarGuessDataTemp> guessUnionList, int stage) {
        UnionWar unionWar = UnionPhaseWarMgr.getUnionWar(activityId);
        if (unionWar == null) {
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }
        if (!checkInGuessTime(stage, activityId)) {
            return GameErrorCode.E_UNION_WAR_ACTIVITY_IS_NOT_GUESS_TIME;
        }
        List<String>  unionList = new ArrayList<>();
        //是否在竞猜列表中
        Map<Long, Map<String, GuessUnionInfo>> guessUnionInfoMap = unionWar.getGuessUnionInfo(stage);
        for (UnionWarActivityServerProto.UnionWarGuessDataTemp baseUnionGuessInfo : guessUnionList) {
            if (!guessUnionInfoMap.containsKey(baseUnionGuessInfo.getServerId())) {
                return GameErrorCode.E_UNION_WAR_ACTIVITY_UNION_NOT_IN_LIST;
            }
            if (!guessUnionInfoMap.get(baseUnionGuessInfo.getServerId()).containsKey(baseUnionGuessInfo.getUnionUid())) {
                return GameErrorCode.E_UNION_WAR_ACTIVITY_UNION_NOT_IN_LIST;
            }
            unionList.add(baseUnionGuessInfo.getUnionUid());
        }
        if (!unionWarGuessMap.containsKey(activityId)) {
            unionWarGuessMap.put(activityId, new ConcurrentHashMap<>());
        }
        if (!unionWarGuessMap.get(activityId).containsKey(stage)) {
            unionWarGuessMap.get(activityId).put(stage, new UserUnionWarGuess(player, activityId, stage, null));
        }
        try {
            //竞猜日志
            AutoLogMgr.add(new LogUnionWarActivityGuess(player.getUserId(), activityId, stage, StringUtils.listToString(unionList, ";")));
        }catch (Exception e){
            log.error(e.getMessage(), e);
        }
        UserUnionWarGuess userUnionWarGuess = unionWarGuessMap.get(activityId).get(stage);
        userUnionWarGuess.guess(guessUnionList);
        return 0;
    }

    /**
     * 竞猜领奖
     * 注意分组id，按竞猜内容所属分组去判断结果
     * @param activityId 活动ID
     * @param msg        排行榜数据
     * @param stage      阶段
     */
    public ActivityRewardResult getGuessReward(int activityId, CrossActivityProto.UnionWarRankMsgMsg msg, int stage, boolean isCrossNotify) {
        ActivityRewardResult result = new ActivityRewardResult();
        UnionWar unionWar = UnionPhaseWarMgr.getUnionWar(activityId);
        if (unionWar == null) {
            result.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            return result;
        }
        //当前阶段判断
        if (!checkInGuessRewardTime(stage, activityId)) {
            result.setRet(GameErrorCode.E_UNION_WAR_ACTIVITY_IS_NOT_GUESS_REWARD_TIME);
            return result;
        }
        if (!unionWarGuessMap.containsKey(activityId)) {
            result.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            return result;
        }
        if (!unionWarGuessMap.get(activityId).containsKey(stage)) {
            result.setRet(GameErrorCode.E_UNION_WAR_ACTIVITY_IS_NOT_GUESS_REWARD_TIME);
            return result;
        }
        UserUnionWarGuess userUnionWarGuess = unionWarGuessMap.get(activityId).get(stage);
        return userUnionWarGuess.getReward(msg, isCrossNotify);
    }

    /**
     * 领取跨服冲榜活动奖励
     * @param unionId 弃用，客户端的不准，由服务端决定
     */
    public ActivityRewardResult getRankReward(int activityId, int conditionId, boolean isCrossNotify, int myRank,String unionId) {
        ActivityRewardResult result = new ActivityRewardResult();
        ActivityInfo activityInfo = UnionWarActivityMgr.getOpenActivityInfo(activityId);
        if (activityInfo == null) {
            result.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            return result;
        }
        Map<Integer, UnionWarActivityData> dataMap = activityDataMap.get(activityId);
        if (dataMap == null) {
            result.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            return result;
        }
        ActivityConditionInfo activityConditionInfo = UnionPhaseWarMgr.getActivityConditionInfo(activityId, conditionId);
        if (activityConditionInfo == null) {
            result.setRet(GameErrorCode.E_ACTIVITY_GET_REWARD_CONDITION_ERROR);
            return result;
        }
        UnionWarActivityData activityData = dataMap.get(activityConditionInfo.getType());
        if (null == activityData) {
            result.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            return result;
        }
        int phase = UnionWarActivityMgr.getPhaseByConditionType(activityConditionInfo.getType());
        UnionWar unionWar = UnionPhaseWarMgr.getUnionWar(activityId);
        if (unionWar == null) {
            result.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            return result;
        }

        if (!unionWar.checkInGetRewardTime(phase)) {//不在领奖期
            result.setRet(GameErrorCode.E_ACTIVITY_NO_IN_GET_REWARD_TIME);
            return result;
        }
        UserActivityConditionData conditionData = activityData.getFirstConditionData();
        if(null == conditionData){
            result.setRet(GameErrorCode.E_ACTIVITY_NO_JOIN);
            return result;
        }
        if (conditionData.isGetReward()) {
            result.setRet(GameErrorCode.E_ACTIVITY_REWARD_IS_GET);
            return result;
        }
        unionId = unionWar.isCanGetRewardMember(unionId, phase, getUserId());
        if (unionId.isEmpty()) {
            unionId = GameUnionActivityGroupMgr.getUnionUid(activityId, getUserId());
            if(StringUtils.isNullOrEmpty(unionId)) {
                result.setRet(GameErrorCode.E_ACTIVITY_NO_JOIN);
                return result;
            }
        }

        if(!isCrossNotify) {
            //发送请求到跨服获取排名
            CrossActivityProto.CrossActivityGetRewardReqMsg.Builder reqMsg = CrossActivityProto.CrossActivityGetRewardReqMsg.newBuilder();
            reqMsg.setActivityId(activityId);
            reqMsg.setConditionId(conditionData.getConditionId());
            reqMsg.setUnionUid(unionId);
            //YanQuMessage pkg = YanQuMessageUtils.buildMessage(Protocol.C_CROSS_UNION_WAR_GET_REWARD, reqMsg);
            //GamePlayerMgr.sendChannelPacket(player.getUserId(), pkg);
            player.sendUnionActivityGroupPacket(Protocol.C_CROSS_UNION_WAR_GET_REWARD, reqMsg, activityId);
            return result;
        }else {
            ActivityConditionInfo conditionInfo = UnionPhaseWarMgr.getActivityConditionInfoByRank(activityId, activityConditionInfo.getType(), myRank);
            if(null == conditionInfo) {
                result.setRet(GameErrorCode.E_ACTIVITY_CONDITION_NO_COMPLETE);
                return result;
            }
            int position = GameUnionActivityGroupMgr.getUnionPosition(activityId, player.getUserId());
            UnionWarRankMember unionWarRankMember = unionWar.getUnionWarRankMember(unionId, phase, player.getUserId());
            if(unionWarRankMember != null){
                position = unionWarRankMember.getPositionId();
            }
            if (position == eUnionPosition.Master.getValue()) {
                player.getModule(CurrencyModule.class).addCurrency(conditionInfo.getMasterReward(), eLogMoneyType.Activity, eLogMoneyType.UnionWarActivityRankReward);
                result.setReward(conditionInfo.getMasterRewardStr());

            } else {
                player.getModule(CurrencyModule.class).addCurrency(conditionInfo.getReward(), eLogMoneyType.Activity, eLogMoneyType.UnionWarActivityRankReward);
                result.setReward(conditionInfo.getRewardStr());
            }

            String rewardStr = result.getReward();
            if (rewardStr != null) {
                Property property = PropertyHelper.parseStringToProperty(rewardStr);
                if (property != null) {
                    //记录跨服称号包含的区服id
                    property.getGoods().forEach((k, v) -> {
                        if (GoodsMgr.isDecorationGoods(k)) {
                            player.getModule(DecorationModule.class).setServerIds(k, activityInfo.getActivityId(), activityInfo.getServerListStr());
                        }
                    });
                    player.getModule(BanquetModule.class).getCrossBanquetInvitationReward(rewardStr, activityInfo.getServerListStr());
                    CrossUnionMgr.getRewardHonourItem(rewardStr, activityInfo, myRank, unionId, getUserId());
                }
            }

            conditionData.setGetReward(true);
            onActivityDataChange(activityData);
            activityData.finish(conditionData.getConditionId());
            result.setActivityId(activityId);
            result.setConditionId(conditionInfo.getConditionId());
            LogMgr.addLogActivityReward(player.getUserId(), activityId, activityInfo.getType(), activityInfo.getChildType(),
                    activityConditionInfo.getConditionId(), myRank, false, result.getReward());
            return result;
        }
    }

    public void initSystem() {
        syncActivity();
        for(ActivityInfo activityInfo : UnionWarActivityMgr.getOpenActivityInfo()){
            syncActivityConfigData(activityInfo);
            syncUserActivityData(activityInfo);
        }
    }

    public void syncData(ActivityInfo activityInfo) {
        if(!SystemOpenMgr.systemOpen(player, eSystemId.UnionWarActivity.getValue())){
            return;
        }
        syncActivityConfigData(activityInfo);
        syncUserActivityData(activityInfo);
    }

    public UnionWarSessionReward getBattleReward(int activityId, int phase, int session){
        List<UnionWarSessionReward> rewardList = getBattleRewardMap().get(activityId);
        if(rewardList != null){
            for(UnionWarSessionReward reward : rewardList){
                if(reward.getPhase() == phase && reward.getSession() == session){
                    return reward;
                }
            }
        }
        return null;
    }

    /**
     * 积分赛自动派遣（临时）
     * @param player
     */
    public void autoDispatchPatrons(GamePlayer player) {
        //获取门客列表
        List<UserPatrons> userPatronsList = player.getModule(PatronsModule.class).getUserPatronsList();
        int patronsNum = 0;
        BigInteger silverBigInteger = player.getUserInfo().getSilver();
        long silver = silverBigInteger.longValue() / 10000;
        for(Map.Entry<Integer, UnionWar> warEntry : UnionPhaseWarMgr.getUnionWarMap().entrySet()){
            UnionWar unionWar = warEntry.getValue();
            CurrentTimeInfo currentTimeInfo = unionWar.getCurrentTimeInfo();
            if(currentTimeInfo.getTimeInfo() != null && currentTimeInfo.getPeriodType() == eTimeInfoPeriodType.PrepareTime && currentTimeInfo.getTimeInfo().getType() == 1){
                //按场次派遣
                for(int session = currentTimeInfo.getTimeInfo().getSession(); session <= unionWar.getAllSession(1); session++){
                    if(session == 0){
                        continue;
                    }
                    if(patronsNum >= userPatronsList.size()){
                        break;
                    }
                    int patronsId = userPatronsList.get(patronsNum).getPatronsId();
                    UserPatronsSendTimes sendTimes = unionWar.getUserPatronsSend(player.getUserId(), patronsId);
                    if(sendTimes != null && sendTimes.getTimes() > 0){
                        patronsNum++;
                        session--;
                        continue;
                    }
                    List<Integer> patronsList = new ArrayList<>();
                    patronsList.add(patronsId);
                    String unionUid = GameUnionActivityGroupMgr.getUnionUid(unionWar.getActivityInfo().getActivityId(), player.getUserId());
                    unionWar.dispatchPatrons(player, unionUid, 1, session, patronsList);
                    if(patronsNum % 3 == 0){
                        unionWar.dispatchUserGoods(player, unionUid, 1, session, eItemId.UNION_WAR_ACTIVITY_BSYZ_JN.getValue());
                    }else if(patronsNum % 3 == 1){
                        unionWar.dispatchUserGoods(player, unionUid, 1, session, eItemId.UNION_WAR_ACTIVITY_NYSB_JN.getValue());
                    }else if(patronsNum % 3 == 2){
                        unionWar.dispatchUserGoods(player, unionUid, 1, session, eItemId.UNION_WAR_ACTIVITY_SRPZ_JN.getValue());
                    }
                    unionWar.donateSilver(player, unionUid, 1, session, BigInteger.valueOf(silver));
                    patronsNum++;
                }
            }
        }
    }
}
